<template>
  <div class="bg-[var(--el-bg-color)] w-1/1 h-1/1 overflow-auto p-40px flex flex-row">
    <viewer @buttons="getButtons" :menu="newMenu" class="mr-50px"></viewer>
    <view-editor ref="veRef" :params="nowMenu" @submit-menu="submit"></view-editor>
  </div>
</template>

<script setup lang="ts">
import Viewer from "./components/viewer/index.vue";
import viewEditor from "./components/viewEditor/index.vue";
import { onBeforeMount, ref } from "vue";
import { buttons, Menu } from "./interface";
import { createMenu, getMenu } from "@/api/modules/wechat";
import { ElMessage } from "element-plus";
// 当前的菜单配置
const veRef = ref<InstanceType<typeof viewEditor> | null>();

// 获取当前的按钮配置
const nowMenu = ref<{ menu: { button: buttons[] }; key: string }>();
const getButtons = (params: { menu: { button: buttons[] }; key: string }) => {
  console.log(params);
  nowMenu.value = params;
};

const submit = async () => {
  try {
    await createMenu({ button: nowMenu.value?.menu.button as any });
    ElMessage.success("成功");
  } catch (error) {}
};

const list = ref<buttons[]>([]);
const newMenu = ref<Menu>();

// 处理列表
const operaMenuList = (list: buttons[]) => {
  let newList = JSON.parse(JSON.stringify(list));
  let menu: Menu = { button: [] };
  console.log(newList);
  for (let i = 0; i < newList.length; i++) {
    if (newList[i].p_key === "") {
      menu.button.push(newList[i]);
    }
  }
  for (let i = 0; i < menu.button.length; i++) {
    for (let j = 0; j < newList.length; j++) {
      if (newList[j].p_key === menu.button[i].key) {
        if (!menu.button[i].sub_button) {
          menu.button[i].sub_button = [];
        }
        menu.button[i].sub_button.push(newList[j]);
      }
    }
  }
  newMenu.value = menu;
};
// 当前最大值
const menuList = async () => {
  const { data } = await getMenu();
  list.value = [...(data as buttons[])];
  operaMenuList(list.value);
};

onBeforeMount(() => {
  menuList();
});
</script>

<style></style>
